package com.sudo.common.validenum;

import com.sudo.common.exception.ValidateException;
import com.sudo.common.utils.PatternUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author 为道日损 2020-06-17 21:12
 * webSite：https://www.sudo.ren
 */
public class NotBlankThenPatternValidator implements ConstraintValidator<NotBlankThenPattern, Object> {

    private String regexp;

    @Override
    public void initialize(NotBlankThenPattern notBlankThenPattern) {
        regexp = notBlankThenPattern.regexp();
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext context) {
        if (o == null) {
            return true;
        }
        if (StringUtils.isBlank(o.toString())) {
            return true;
        }
        if (!(o instanceof String)) {
            throw new ValidateException("@NotBlankThenPattern只能修饰String类型");
        }
        return PatternUtil.isMatches(regexp, o.toString());
    }
}
